package ddz.logic.game;

import com.kaka.notice.annotation.Handler;
import ddz.constants.Crypto;
import ddz.constants.ErrCode;
import ddz.constants.ErrLevel;
import ddz.constants.OpCode;
import ddz.db.dao.UserDao;
import ddz.db.entity.UserInfo;
import ddz.net.LogicDataHandler;
import ddz.net.ProtocolMessage;
import ddz.numerical.manager.ConfPlaceInfoManager;
import ddz.numerical.manager.ConfSingleInfoManager;
import ddz.numerical.pojo.ConfPlaceInfo;
import ddz.numerical.pojo.ConfSingleInfo;
import ddz.protos.GameBenefit;
import ddz.utils.DateTimeUtils;

import java.time.LocalDateTime;

/**
 * 领取救济金
 *
 * @author zkpursuit
 */
@Handler(cmd = OpCode.cmd_benefit_get)
public class GetBenefitHandler extends LogicDataHandler {
    @Override
    public void execute(ProtocolMessage msg) throws Exception {
        Long uid = msg.uid();
        UserDao userDao = this.retrieveProxy(UserDao.class);
        UserInfo userInfo = userDao.getUserInfo(uid);
        if (userInfo == null) {
            return;
        }
        Long timestramp = userInfo.getBenefitDate();
        boolean resetCount = false; //是否需要重置救济领取次数
        boolean updateUserData = false; //是否需要更新玩家数据
        if (timestramp == null || timestramp <= 0) {
            resetCount = true;
        } else {
            LocalDateTime ldt = DateTimeUtils.toLocalDateTime(timestramp, DateTimeUtils.CH_ZONE);
            long offsetDays = DateTimeUtils.between(ldt, LocalDateTime.now(), DateTimeUtils.Interval.DAY);
            if (offsetDays >= 1) resetCount = true;
        }
        if (resetCount) {
            if (userInfo.getBenefitCount() != 2) {
                userInfo.setBenefitCount(2);
            }
            userInfo.setBenefitDate(System.currentTimeMillis());
            updateUserData = true;
        }
        if (userInfo.getBenefitCount() > 0) {
            ConfPlaceInfoManager confPlaceInfoManager = this.retrieveProxy(ConfPlaceInfoManager.class);
            ConfPlaceInfo confPlaceInfo = confPlaceInfoManager.getConfPlaceInfo(1, 1);
            if (confPlaceInfo != null && userInfo.getGold() >= confPlaceInfo.getMinGold()) {
                if (updateUserData) userDao.insertOrUpdateUser(userInfo);
                sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.no_benefit_conditions);
                return;
            }
            ConfSingleInfoManager confSingleInfoManager = this.retrieveProxy(ConfSingleInfoManager.class);
            ConfSingleInfo confSingleInfo = confSingleInfoManager.getConfSingleInfo();
            int benefitGold = 0; //补助的游戏豆数量
            if (confSingleInfo != null) benefitGold = confSingleInfo.getBenefitGold();
            if (benefitGold <= 0) benefitGold = 50000;
            userInfo.setBenefitCount(userInfo.getBenefitCount() - 1);
            userInfo.setBenefitDate(System.currentTimeMillis());
            userInfo.setGold(userInfo.getGold() + benefitGold);
            userDao.insertOrUpdateUser(userInfo);
            GameBenefit.ScGetBenefit scGetBenefit = GameBenefit.ScGetBenefit.newBuilder()
                    .setRemaingCount(userInfo.getBenefitCount())
                    .setOffsetBeans(benefitGold)
                    .setTotalsBeans(userInfo.getGold())
                    .build();
            byte[] respBytes = scGetBenefit.toByteArray();
            this.sendData(msg.ctx(), Crypto.isCrypto, opcode(), respBytes);
        } else {
            if (updateUserData) userDao.insertOrUpdateUser(userInfo);
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.no_benefit);
        }
    }

    /**
     * 发放救助金，由服务器主动推送，调用1023号协议
     * @param userInfo
     * @return
     */
    protected void provideBenefit(UserInfo userInfo, boolean updateUserInfo) {
        ConfSingleInfoManager confSingleInfoManager = this.retrieveProxy(ConfSingleInfoManager.class);
        ConfSingleInfo confSingleInfo = confSingleInfoManager.getConfSingleInfo();
        int benefitGold = 0; //补助的游戏豆数量
        if (confSingleInfo != null) benefitGold = confSingleInfo.getBenefitGold();
        if (benefitGold <= 0) benefitGold = 50000;
        userInfo.setBenefitCount(userInfo.getBenefitCount() - 1);
        userInfo.setBenefitDate(System.currentTimeMillis());
        userInfo.setGold(userInfo.getGold() + benefitGold);
        if(updateUserInfo) {
            UserDao userDao = this.retrieveProxy(UserDao.class);
            userDao.insertOrUpdateUser(userInfo);
        }
        GameBenefit.ScGetBenefit scGetBenefit = GameBenefit.ScGetBenefit.newBuilder()
                .setRemaingCount(userInfo.getBenefitCount())
                .setOffsetBeans(benefitGold)
                .setTotalsBeans(userInfo.getGold())
                .build();
        byte[] respBytes = scGetBenefit.toByteArray();
        int opcode = Integer.parseInt(OpCode.cmd_benefit_get);
        this.sendData(userInfo.getUid(), Crypto.isCrypto, opcode, respBytes);
    }

    /**
     * 是否可领取救济金
     *
     * @param userInfo
     * @param placeMinGold 是否依据最低场次最少游戏豆要求判定救济需求
     * @return true表示需要救济
     */
    protected boolean isCanGetBenefit(UserInfo userInfo, boolean placeMinGold) {
        if (userInfo == null) return false;
        int nextStep = 0;
        ConfPlaceInfoManager confPlaceInfoManager = this.retrieveProxy(ConfPlaceInfoManager.class);
        ConfPlaceInfo confPlaceInfo;
        if (placeMinGold) {
            confPlaceInfo = confPlaceInfoManager.getConfPlaceInfo(1, 1);
            if (confPlaceInfo != null && userInfo.getGold() >= confPlaceInfo.getMinGold()) {
                return false;
            }
        } else {
            if (userInfo.getGold() > 0) return false;
        }
        int benefitCount = userInfo.getBenefitCount();
        Long timestramp = userInfo.getBenefitDate();
        if (timestramp == null || timestramp <= 0) {
            benefitCount = 2;
        } else {
            LocalDateTime ldt = DateTimeUtils.toLocalDateTime(timestramp, DateTimeUtils.CH_ZONE);
            long offsetDays = DateTimeUtils.between(ldt, LocalDateTime.now(), DateTimeUtils.Interval.DAY);
            if (offsetDays >= 1) benefitCount = 2;
        }
        if (benefitCount == 0) {
            return false;
//            if (confPlaceInfo != null) {
//                if (userInfo.getGold() < confPlaceInfo.getMinGold()) {
//                    ConfShopInfoManager confShopInfoManager = this.retrieveProxy(ConfShopInfoManager.class);
//                    int needGold = confPlaceInfo.getMinGold() - userInfo.getGold();
//                    ConfShopInfo shopInfo = confShopInfoManager.getConfShopInfoByMinGold(needGold);
//                    if (userInfo.getDiam() >= shopInfo.getPrice()) {
//                        nextStep = 1;
//                    } else {
//                        nextStep = 2;
//                    }
//                }
//            }
        }
        byte[] respBytes = GameBenefit.ScBenefit.newBuilder()
                .setCounted(2 - benefitCount)
                .setMaxCount(2)
                .setNextStep(nextStep)
                .build().toByteArray();
        int opcode = Integer.parseInt(OpCode.cmd_benefit);
        this.sendData(userInfo.getUid(), Crypto.isCrypto, opcode, respBytes);
        return true;
    }
}
